
//
//  BDFansViewController.m
//  BadBoy
//
//  Created by wen on 2017/3/21.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDFansViewController.h"
#import "BDUserModel.h"
#import "BDUserInfoViewController.h"

@interface BDFansViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    BOOL isChangeSegementRequest;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *titleview;
@property (nonatomic, strong) NSMutableArray *datasource;

@property (nonatomic, strong) NSMutableDictionary *dictionary;
@property (nonatomic, strong) NSMutableArray *startPageArray;

@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;

@end

@implementation BDFansViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addSubviews];
    
    self.startPageArray = @[@"1", @"1"].mutableCopy;
    
    self.dictionary = [NSMutableDictionary dictionary];
    
    isChangeSegementRequest = YES;
    [self requestDatasource];
}

- (void)addSubviews{
    self.navigationItem.titleView = self.titleview;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)requestDatasource{
    if (isChangeSegementRequest == YES) {
        [self.indicatorView startAnimating];
        self.tableView.hidden = YES;
        isChangeSegementRequest = NO;
    }
    
    BDUserModel *user = [BDUserModel getCurrentUser];
    NSString *url = [NSString stringWithFormat:@"%@user/%@/%@?page=%@&size=%@", KBDBaseURL,@(user.user_id), self.fansType == BDFansStartTypeGuanzhu ? @"follow" : @"follower", self.startPageArray[self.fansType], self.pageSize];
    NSString *headValid = [BDUserModel getHeaderValidation];
    
    RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    
    [signal subscribeNext:^(id  _Nullable x) {
        self.isEnd = [x[@"is_end"] boolValue];
        self.startPageArray[self.fansType] = [NSString stringWithFormat:@"%@", x[@"next_page"]];
        NSMutableArray *array = x[@"list"];
        NSMutableArray *curDa = self.dictionary[[NSString stringWithFormat:@"%ld", self.fansType]];
        if (curDa == nil) {
            curDa = [NSMutableArray array];
            [self.dictionary setObject:curDa forKey:[NSString stringWithFormat:@"%ld", self.fansType]];
        }
        [curDa addObjectsFromArray:array];
        self.datasource = curDa;
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        [self setTableiewFooterViewStateFor:self.tableView datasourceCount:self.datasource.count];
        [self.tableView reloadData];
        [self.indicatorView stopAnimating];
        self.tableView.hidden = NO;
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
       [self showErrorViewWithTapBlock:^{
           
       }];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datasource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BDFansTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"fansCell" forIndexPath:indexPath];
    NSDictionary *dic = self.datasource[indexPath.row];
    __weak BDFansViewController *weakSelf = self;
    [cell configeWithModel:dic fansType:self.fansType clickBlock:^(NSString *buttonTitle){
        
        NSString *guanzhuUserId = nil;
        if (weakSelf.fansType ==BDFansStartTypeGuanzhu) {
            guanzhuUserId = dic[@"follow"][@"user_id"];
        }else {
            guanzhuUserId = dic[@"follower"][@"user_id"];
        }
        NSString *url = [NSString stringWithFormat:@"%@follow/%@", KBDBaseURL, guanzhuUserId];
        NSString *headValid = [BDUserModel getHeaderValidation];
        //        NSDictionary *para = @{@"id":@(self.model.my_id)};
        [MBManager showLoadingAlert:ASLocalizedString(@"请稍后")clickHidden:NO clickBlock:nil];
        RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
        [signal subscribeNext:^(id  _Nullable x) {
//            [MBManager hideAlert];
            [MBManager showBriefAlert:[NSString stringWithFormat:ASLocalizedString(@"%@成功"), buttonTitle] clickHidden:YES clickBlock:nil];
            //清除所有的数据
            [weakSelf updateCurrentDate];
        }];
        
        [signal subscribeError:^(NSError * _Nullable error) {
//            [MBManager hideAlert];
            [MBManager showBriefAlert:[NSString stringWithFormat:ASLocalizedString(@"%@失败"), buttonTitle] clickHidden:NO clickBlock:nil];
            // BDLog(ASLocalizedString(@"关注操作失败：%@"), error);
        }];
        
    }];
    
    if (indexPath.row == 0) {
        cell.isFirst = YES;
    }else {
        cell.isFirst = NO;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *startDic = self.datasource[indexPath.row];
    NSDictionary *modelDic = nil;
    BOOL isFollow = NO;
    if (self.fansType ==BDFansStartTypeGuanzhu) {
        isFollow = YES;
        modelDic = [startDic objectForKey:@"follow"];
    }else {
        isFollow = [startDic[@"is_followed"] boolValue];
        modelDic = [startDic objectForKey:@"follower"];
    }
    if ([modelDic isEqual:[NSNull null]] || modelDic == nil) {
        return;
    }else{
        BDUserModel *user = [[BDUserModel alloc] init];
        user.user_id = [modelDic[@"user_id"] integerValue];
        user.nickname = modelDic[@"nickname"];
        user.cover = modelDic[@"cover"];
        user.vip_level = [modelDic[@"vip_level"] integerValue];
        __weak BDFansViewController *weakSelf = self;
        BDUserInfoViewController *userVC = [[BDUserInfoViewController alloc] initWithUserID:user.user_id isFollow:isFollow guanzhuBlock:^(BOOL isFollow) {
            [weakSelf updateCurrentDate];
        }];
        [self.navigationController pushViewController:userVC animated:YES];
    }
}

- (void)updateCurrentDate{
    self.dictionary = [NSMutableDictionary dictionary];
    self.startPageArray = @[@"1", @"1"].mutableCopy;
    isChangeSegementRequest = YES;
    [self requestDatasource];
    //调用通知更新关注数量
    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshFansCount" object:nil];
    //发送给首页的，当关注人变更之后，首页关注列表也要跟着变更
    [[NSNotificationCenter defaultCenter] postNotificationName:@"guanzhuChange" object:nil];
}

- (UIView *)titleview{
    if (!_titleview) {
        self.titleview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 44)];
        _titleview.backgroundColor = [UIColor clearColor];
        
        CGFloat buttonWidth = 50;
        
        //下划线
        UIView *lineView = [[UIView alloc]init];
        lineView.backgroundColor = KBDColorBlue;
        
        lineView.width = buttonWidth;
        lineView.height = 2;
        lineView.bottom = _titleview.height;
        lineView.left = 0;
        
        [_titleview addSubview:lineView];
        
        CGFloat startLeft = 10;
        for (int i = 0; i < 2; i++) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            if (i == 0) {
                [button setTitle:ASLocalizedString(@"关注")forState:UIControlStateNormal];
            }else {
                [button setTitle:ASLocalizedString(@"粉丝")forState:UIControlStateNormal];
            }
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:17];
            button.width = buttonWidth;
            button.height = _titleview.height;
            button.left = startLeft;
            button.top = 0;
            [_titleview addSubview:button];
            startLeft = button.right + 10;
            if (i == self.fansType) {
                lineView.left = button.left;
            }
            [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                if (i == self.fansType) {
                    return;
                }
                [UIView animateWithDuration:0.3 animations:^{
                    lineView.left = button.left;
                } completion:^(BOOL finished) {
                    self.fansType = i;
                    NSMutableArray *curDa = self.dictionary[[NSString stringWithFormat:@"%ld", self.fansType]];
                    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
                        [self.datasource removeAllObjects];
                        self.startPageArray[self.fansType] = @"1";
                        [self requestDatasource];
                    }];
                    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                        [self requestDatasource];
                    }];
                    if (curDa.count == 0) {
                        isChangeSegementRequest = YES;
                        [self requestDatasource];
                    }else{
                        self.datasource = curDa;
                        [self.tableView reloadData];
                        [self setTableiewFooterViewStateFor:self.tableView datasourceCount:self.datasource.count];
                    }
                }];
            }];
        }
        _titleview.width = startLeft;
    }
    return _titleview;
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.sectionHeaderHeight = 0;
        _tableView.sectionFooterHeight = 10;
        [_tableView registerClass:[BDFansTableViewCell class] forCellReuseIdentifier:@"fansCell"];
        [self.view insertSubview:_tableView atIndex:0];
    }
    return _tableView;
}

- (UIActivityIndicatorView *)indicatorView{
    if (!_indicatorView) {
        self.indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _indicatorView.hidesWhenStopped = YES;
        _indicatorView.frame = CGRectMake(0, kBDTopHeight, kBDScreenWidth, 50);
        [self.view addSubview:_indicatorView];
    }
    return _indicatorView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
